﻿using System.Collections.Generic;
using Gj;
using UnityEngine;

public class ShowModel : MonoBehaviour
{
    public GameObject camera;
    private GameObject last;
    private readonly Dictionary<string, GameObject> modelMap = new();

    public void Show()
    {
        camera.SetActive(true);
        gameObject.SetActive(true);
    }

    public void Hide()
    {
        camera.SetActive(false);
        gameObject.SetActive(false);
    }

    public void SetModel(string modelName)
    {
        if (StringTools.IsEmpty(modelName)) return;
        if (last != null) last.SetActive(false);
        var item = GetItem(modelName);
        if (item == null) return;
        item.SetActive(true);
        last = item;
    }

    public void SetModel(string modelName, string anim)
    {
        SetModel(modelName);
        PlayAnim(last, anim);
    }

    private GameObject GetItem(string modelName)
    {
        if (!modelMap.ContainsKey(modelName))
            modelMap.Add(modelName, ObjectService.single.MakeSkin(modelName, gameObject));
        return modelMap[modelName];
    }

    private void PlayAnim(GameObject obj, string anim)
    {
        var a = obj.GetComponent<Animator>();
        if (a != null) a.Play(anim);
    }
}